
// manage globalization plan assumptions
// singleton
// action: list, create, edit, view, save, delete, makeActive, makePrivate
var GPAManager = {

	GPAFormBean:"com.ibm.gbms.formbean.gpa.GPAFormBean",
	BPManagerGPA:"com.ibm.gbms.bp.gpa.BPManageGPA",
	/* fields */
	
	// target product/component
	_deliverableID: null,
	
	_deliverableName: null,
	
	_deliverableVersion: null,
	
	_actionGPAIDs:[],
    
    // globalization plan assumptions set json data
    _gpaList: {
		items: []
	},
    
    _gpaStore: {},
	
	_selectedGPAs:[],
    
    init:function(){
   		var showTooltip = function(e){				 
            if (e.cell.index == 1) {
				var msg = e.cellNode.firstChild.data;
                dijit.showTooltip(msg, e.cellNode);
            }
        };
        var hideTooltip = function(e){
            dijit.hideTooltip(e.cellNode);
            // FIXME: make sure that pesky tooltip doesn't reappear!
            // would be nice if there were a way to hide tooltip without regard to aroundNode.
            dijit._masterTT._onDeck = null;
        };
    	dojo.connect(dijit.byId('gpaGrid'), "onCellMouseOver", showTooltip);
		dojo.connect(dijit.byId('gpaGrid'), "onCellMouseOut", hideTooltip);
		
		var hideSortIcon = function() {
			var thElements = dojo.query("th", dojo.byId('gpaGrid'));
			for(var i = 0; i < thElements.length; i ++){
				var th = thElements[i];
				if(th.cellIndex == 0){
					th.childNodes[0].className = "";
				}
			}
		};
		dijit.byId('gpaGrid').canSort = function(index) {  
				  if(Math.abs(index) == 1) return false;
				  return true;
		}
		//discard all the rowclick event
		var rowClick_=dijit.byId('gpaGrid').onRowClick;
		dijit.byId('gpaGrid').onRowClick=function(e){
			
		};
		dojo.connect(dijit.byId('gpaGrid'), "render", hideSortIcon);
		dojo.connect(dijit.byId('gpaGrid'), "update", hideSortIcon);
		dojo.connect(dijit.byId('gpaGrid'), "setStore", hideSortIcon);
		dijit.byId('gpaGrid').update();
		
		
    },
	    
	saveItem:function(value){
		//apply the changed value to the store of the grid
		dijit.byId("gpaGrid").edit.apply();
	},
	
	gpmGridLayout : [{
				defaultCell: { width: 8, editable: true, type: dojox.grid.cells._Widget, styles: 'text-align: right;',height:'20px;'  },
			
				rows: [
						{ name: 'Select', styles: 'text-align: center;',field: 'select', type:dojox.grid.cells.Bool, width: '5%'},
						{ name: 'Name', styles: '', field: 'name', type: dojox.grid.cells.TextBox, width: '17%', editable: false},
						{ name: 'Version', styles: '', field: 'version', type: dojox.grid.cells.TextBox, width: '8%', editable: false},
						{ name: 'ID#', styles: '', field: 'ID', width: '8%', editable: false},
						{ name: 'Marketing status', styles: '', field: 'status', 
							type: dojox.grid.cells.ComboBox, width: '13%',
							options: ["Open", "LA/ESP", "Previewed", "Use Ann", "Use GA", "WW Ann", "WW GA","Withdrawal Announced", "Withdrawal from Marketing", "Withdrawal from Service"],
							widgetProps:{onBlur:function(){var _value=this.getValue();GPAManager.saveItem("phase "+_value);}}},
						{ name: 'GB18030 phase 1 complaint', styles: '', field: 'phase', 
							type: dojox.grid.cells.ComboBox, width: '18%',options:["yes","no"],
							widgetProps:{onBlur:function(){var _value=this.getValue();GPAManager.saveItem("phase "+_value);}}},
						{ name: 'Classification', styles: '', field: 'Classification', 
							type: dojox.grid.cells.ComboBox, width: '10%',options:["Flagship", "Non-key", "Legacy"],
							widgetProps:{onBlur:function(){var _value=this.getValue();GPAManager.saveItem("phase "+_value);}}},
						{ name: 'Acquisition?', styles: '', field: 'Acquisition', 
							type: dojox.grid.cells.ComboBox, width: '10%',options:["yes","no"],
							widgetProps:{onBlur:function(){var _value=this.getValue();GPAManager.saveItem("phase "+_value);}}},
						{ name: 'Data source', styles: '', field: 'Data', type: dojox.grid.cells.TextBox, width: '13%', editable: false}
				]
			}],
			
	getGPANameById:function(wizid){
		for(var i=0;i<this._gpaList.items.length;i++){
			var item = this._gpaList.items[i];
			if(item.wizardID == wizid){
				return item.name;
			}
		}
	},
	getIsActiveById:function(wizid){
		for(var i=0;i<this._gpaList.items.length;i++){
			var item = this._gpaList.items[i];
			if(item.wizardID == wizid){
				return item.isActive;
			}
		}
	},
	setSelectedGPAs:function(){
		GPAManager._selectedGPAs = [];
		GPAManager._gpaStore.fetch({
			onComplete: function(items, request){
				for (var i = 0; i < items.length; i++) {
					var item = items[i];
					if(item.select[0] == true)
						GPAManager._selectedGPAs.push(item);
				}
			}
		});
		
	},
	getSelectedGPAIDs:function(){
		var gpaIDs = [];
		for(var i = 0 ;i < GPAManager._selectedGPAs.length; i++){
			var item = GPAManager._selectedGPAs[i];
			gpaIDs.push(item.wizardID);
		}
		return gpaIDs;
	},
	cellChanged:function(item, attribute, oldValue, newValue){
		if(attribute == "select"){
			if (oldValue == false && newValue == true) {
				dijit.byId("gpaGrid").selection.addToSelection(item);  // only for the first line of the grid
			}
			else if(oldValue == true && newValue == false){
				dijit.byId("gpaGrid").selection.deselect(item);
			}
			this.setSelectedGPAs();
			this.select();
		}
		
		if (oldValue == newValue)
	   {
	      console.log("Attribute: " + attribute + " on package: " + item.name + "did not change.");
		  
		  
	   }
	   else
	   {  
	      // TODO: Save the updated data.
	      console.log("Attribute: " + attribute + " on plan: " + item.name + " was changed from: " + oldValue + " to: " + newValue);  
	   
	   }
	},
	
	select:function(wizid){
		var selectedNum = GPAManager._selectedGPAs.length;
		if(selectedNum>1){
			dojo.byId("edit_gd").disabled="true";
			dojo.byId("view_gd").disabled="true";
			dojo.byId("view_gd_css").className="button-gray";
			dojo.byId("edit_gd_css").className="button-gray";
		}
		else if(selectedNum==1){
			dojo.forEach(
    			dojo.query("input[type=button]", "bt_gd"),
    			function(selectTag) {
        			selectTag.disabled = false;
    			}
			);
			dojo.forEach(
    			dojo.query("div", "bt_gd"),
    			function(selectTag) {
        			selectTag.className="button-blue";
    			}
			);
			
			var isActive = GPAManager._selectedGPAs[0].isActive[0];
			if(isActive == true){
				dojo.byId("make_active").disabled = "true";
				dojo.byId("make_active_css").className = "button-gray";
			}else{
				dojo.byId("make_draft").disabled = "true";
				dojo.byId("make_draft_css").className = "button-gray";
			}
		}else{
			dojo.forEach(
    			dojo.query("input[type=button]", "bt_gd"),
    			function(selectTag) {
        			selectTag.disabled = true;
    			}
			);
			dojo.forEach(
    			dojo.query("div", "bt_gd"),
    			function(selectTag) {
        			selectTag.className="button-gray";
    			}
			);
		}
	},
	
	
	loadGPAPRecoreds:function(){
		if(GPAManager._deliverableID == null){
			return;
		}
		GPAManager._gpaList.items = [];
		
		var name_version = Deliverable.getNameVersion(this._deliverableID);
		var strArray = name_version.split(";");
		GPAManager._deliverableName = strArray[0];
		GPAManager._deliverableVersion = strArray[1];
		var datawrapper = {};
        datawrapper[Constant.POST_TYPE]=Constant.Action.Load;
        datawrapper["deliverableID"] = GPAManager._deliverableID;
		
        var kw = {
            url: Constant.POST_URL,
            handleAs: "json",
            content: Util.preparePostData(GPAManager.GPAFormBean, GPAManager.BPManagerGPA, datawrapper),
            preventCache: true,
            load: dojo.hitch(this, this.renderGPARecords)
        };
        dojo.xhrPost(kw);
	},
	renderGPARecords:function(json){ 
		var gpaList=json[Constant.RESPONSE_GPALIST];
		for(var i=0;i<gpaList.length;i++){
			var data = gpaList[i];
			if(gpaList[i].GB18030Phase1Complaint == true){
				data.GB18030Phase1Complaint = "yes";
			}else{
				data.GB18030Phase1Complaint = "no";
			}
			if(gpaList[i].acquisition == true){
				data.acquisition = "yes";
			}else{
				data.acquisition = "no";
			}
			data.select=false;
			if(GPAManager._actionGPAIDs.length>0)
				for(var j=0;j<GPAManager._actionGPAIDs.length;j++){
					var actionGPAID = GPAManager._actionGPAIDs[j];
					if(actionGPAID!=null&&actionGPAID == data.wizardProjectID){
						data.select=true;
					}
				}
			var rowItem = {
				isActive:data.isActive,
				wizardID:data.wizardProjectID,
				select:data.select,
				name:GPAManager._deliverableName, 
				version:GPAManager._deliverableVersion , 
				ID:GPAManager._deliverableID,
				status:data.marketingStatus, 
				phase:data.GB18030Phase1Complaint, 
				Classification:data.classification, 
				Acquisition:data.acquisition, 
				Data:"Clearing House" 
			}
			GPAManager._gpaList.items.push(rowItem);
		}
		/***
		if(dojo.byId("gpaFilter").value!="All plans"){
			if(((dojo.byId("gpaFilter").value==("Active") && !data.isActive) || (dojo.byId("gpaFilter").value==("Draft") && data.isActive))){
				dijit.byId("gpaFilter").setValue("All plans");
			}
		}
		**/
			
		GPAManager.filter();
			/**
    		GPAManager._gpaStore = {
    			items: [
    					{
    					select:"<input type='checkbox' dojoType='dijit.form.CheckBox' name='radio2' id='grid_10' onClick='GPAManager.select()'/>", 
						name:GPAManager._deliverableName, version:GPAManager._deliverableVersion , ID:GPAManager._deliverableID, status:"open", 
						phase:"yes", Classification:"Flagship", Acquisition:"yes", Data:"Clearing House"
						},
						{
    					select:"<input type='checkbox' dojoType='dijit.form.CheckBox' name='radio2' id='grid_10' onClick='GPAManager.select()'/>", 
						name:"IBM WebSphere Business Modeler Advanced", version: "1.0", ID:"FAD11245", status:"open", 
						phase:"yes", Classification:"Flagship", Acquisition:"yes", Data:"Clearing House"
						}
    			]
    		};
    		**/
			
			//GPAManager._gpaStore = new dojo.data.ItemFileWriteStore({data: GPAManager._gpaList});
			//dojo.connect(GPAManager._gpaStore, "onSet", GPAManager,"cellChanged");
			//dijit.byId("gpaGrid").setStore(GPAManager._gpaStore);
			
			//this.setSelectedGPAs();
			//this.select();
			
			
	},
	filter:function(){
		var filter = dojo.byId("gpaFilter").value;
		GPAManager._gpaStore = {};		
		var filterData = {
			items: []
		};
		
		for(var i = 0; i < GPAManager._gpaList.items.length; i ++){
			var item = GPAManager._gpaList.items[i];
			if(filter == 'All plans'){
				filterData.items.push(item);
			}else if(filter == 'Active' && (item.isActive[0] == true || item.isActive == true)){
				filterData.items.push(item);
				
			}else if(filter == 'Draft' && (item.isActive[0] == false || item.isActive == false)){
				filterData.items.push(item);
			}
							
		}
		
		GPAManager._gpaStore = new dojo.data.ItemFileWriteStore({data: filterData});
		dojo.connect(GPAManager._gpaStore, "onSet", GPAManager,"cellChanged");
		dijit.byId("gpaGrid").setStore(GPAManager._gpaStore);
		this.setSelectedGPAs();
			this.select();
	},
	
	renderBlankPlans:function(){
		GPAManager._gpaList.items = [];
		GPAManager._deliverableID = null;
		GPAManager.filter();
	},
	/* action methods */
    list: {
    	submit: function(_deliverableID) {
			//if(GPAManager._gpaStore.declaredClass!=null)
			//	GPAManager.saveItem();
			if(!_deliverableID){
				GPAManager.renderBlankPlans();
				return;
			}
			if(GPAManager._deliverableID == _deliverableID)
				return;
			dijit.byId("gpaGrid").selection.deselect(0);
    		GPAManager._deliverableID = _deliverableID;
			GPAManager._actionGPAIDs = [];
			GPAManager._selectedGPAs = [];
			GPAManager.loadGPAPRecoreds();
			//dijit.byId("gpaFilter").setValue("All plans");	
			
    	},
    	
    	callback: function(josn) {
    		if(json[Constant.POST_RESULT]==Constant.POST_ERROR){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
    		GPAManager.loadGPAPRecoreds();
    	}
    	
    },    
    
    create: {
    	submit: function() {
    		//window.location = 'create_plan.jsp';
    		if(GPAManager._deliverableID == null){
    			alert("Please select a deliverable croducts or components to create plane.");
    			return false;
    		}
    		var datawrapper = {};
	        datawrapper[Constant.POST_TYPE]=Constant.Action.Create;
	        datawrapper["deliverableID"] = GPAManager._deliverableID;
	        var kw = {
	            url: Constant.POST_URL,
	            handleAs: "json",
	            content: Util.preparePostData(GPAManager.GPAFormBean, GPAManager.BPManagerGPA, datawrapper),
	            preventCache: true,
	            load: dojo.hitch(this, this.callback)
	        };
	        dojo.xhrPost(kw);
	        
	    },
    	
    	callback: function(json) {
			if(json[Constant.POST_RESULT]==Constant.POST_RESULT_VALIDATION_ERRORMSG){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
    		if(json[Constant.POST_RESULT]==Constant.POST_ERROR){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
			
    		var gpaList=json[Constant.RESPONSE_GPALIST];
			var data = gpaList[0];
			var wizardProjectID = data["wizardProjectID"];
			var viewMode = "Write"
			window.location = window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode;
	    }
    },
    
    view: {
    	submit: function() {
			var wizardProjectID = GPAManager._selectedGPAs[0].wizardID[0];
			var viewMode = "Readonly"
			//alert(window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode);
			window.location = window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode;
		},
    	
    	callback: function() {}
    },
    
    edit: {
    	submit: function() {
			var wizardProjectID = GPAManager._selectedGPAs[0].wizardID[0];
			var viewMode = "Write"
			//alert(window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode);
			dojo.global.qaDeliverableName = this._deliverableName;
			window.location = window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode;
		},
    	
    	callback: function() {}
    },
    
    save: {
    	submit: function() {},
    	
    	callback: function() {}
    },

    showDeleteDlg:function(){
		GPAManager._actionGPAIDs = [];
		var deleteList = dojo.byId("gpaDeleteList");
		var htmlString = "";
		for(var i = 0; i<GPAManager._selectedGPAs.length; i++){
			var item = GPAManager._selectedGPAs[i];
			GPAManager._actionGPAIDs.push(item.wizardID[0]);
			htmlString=htmlString.concat("<li>"+item.name+"</li>");
		}
		deleteList.innerHTML = htmlString;
		dijit.byId('deleteDlg').show();
		dojo.byId("delButton").focus();
	},
    deletePlan: {
    	submit: function() {
			var datawrapper = {};
	        datawrapper[Constant.POST_TYPE]=Constant.Action.Delete;
	        datawrapper[Constant.PARAMETER_TARGET_WIZARDPROJECTID_ARRAY] = GPAManager._actionGPAIDs;
	        var kw = {
	            url: Constant.POST_URL,
	            handleAs: "json",
	            content: Util.preparePostData(GPAManager.GPAFormBean, GPAManager.BPManagerGPA, datawrapper),
	            preventCache: true,
	            load: dojo.hitch(this, this.callback)
	        };
	        dojo.xhrPost(kw);
			
		},
    	
    	callback: function(json) {
			dijit.byId("deleteDlg").hide();
			if(json[Constant.POST_RESULT]==Constant.POST_ERROR){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
			GPAManager.loadGPAPRecoreds();
		}
    },
    showActiveDlg:function(){
		GPAManager._actionGPAIDs = [];
		for(var i = 0; i<GPAManager._selectedGPAs.length; i++){
			var item = GPAManager._selectedGPAs[i];
			GPAManager._actionGPAIDs.push(item.wizardID[0]);
		}
		dijit.byId('activeDlg').show();
	},
    makeActive: {
    	submit: function() {
			var datawrapper = {};
	        datawrapper[Constant.POST_TYPE]=Constant.Action.MakeActive;
	        datawrapper[Constant.PARAMETER_TARGET_WIZARDPROJECTID_ARRAY] = GPAManager._actionGPAIDs;
	        var kw = {
	            url: Constant.POST_URL,
	            handleAs: "json",
	            content: Util.preparePostData(GPAManager.GPAFormBean, GPAManager.BPManagerGPA, datawrapper),
	            preventCache: true,
	            load: dojo.hitch(this, this.callback)
	        };
	        dojo.xhrPost(kw);
		},
    	
    	callback: function(json) {
			dijit.byId("activeDlg").hide();
			if(json[Constant.POST_RESULT]==Constant.POST_ERROR){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
			GPAManager.loadGPAPRecoreds();
		}
    },
    showDraftDlg:function(){
		GPAManager._actionGPAIDs = [];
		for(var i = 0; i<GPAManager._selectedGPAs.length; i++){
			var item = GPAManager._selectedGPAs[i];
			GPAManager._actionGPAIDs.push(item.wizardID[0]);
		}
		dijit.byId('draftDlg').show(); 
	},
    makeDraft: {
    	submit: function() {
			var datawrapper = {};
	        datawrapper[Constant.POST_TYPE]=Constant.Action.MakeDraft;
	        datawrapper[Constant.PARAMETER_TARGET_WIZARDPROJECTID_ARRAY] = GPAManager._actionGPAIDs;
	        var kw = {
	            url: Constant.POST_URL,
	            handleAs: "json",
	            content: Util.preparePostData(GPAManager.GPAFormBean, GPAManager.BPManagerGPA, datawrapper),
	            preventCache: true,
	            load: dojo.hitch(this, this.callback)
	        };
	        dojo.xhrPost(kw);
		},
    	
    	callback: function(json) {
			dijit.byId("draftDlg").hide();
			if(json[Constant.POST_RESULT]==Constant.POST_ERROR){
				GPAManager.showErrorMsg(json[Constant.POST_RESULT_ERRORMSG]);
				return;
			}
			GPAManager.loadGPAPRecoreds();
		}
    },
	showErrorMsg:function(msg){
		dojo.byId("errorMsg").innerHTML = msg;
		
		dijit.byId("errorDlg").show();
	},
	
	editPlan:function(){
		var wizardProjectID = GPAManager._selectedGPAs[0].wizardID[0];
		var viewMode = "Write"
		//alert(window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode);
		window.location = window.contextRoot+'/faces/user/create_plan.jsp?wpid='+wizardProjectID + '&vm=' + viewMode;
	}
			
			
};